﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.Utils
{
    public class NetUtil
    {
        // 声明IHttpClientFactory
        private readonly IHttpClientFactory clientFactory;

        // 构造方法注入 IHttpClientFactory
        public NetUtil(IHttpClientFactory clientFactory)
        {
            this.clientFactory = clientFactory;
        }

        public async Task Test()
        {
            // 事先准备的一个 Web Api
            var url = "http://127.0.0.1:54327/net/mytest";
 
            await GetApiContent(url);
        }

        private async Task GetApiContent(string url)
        {
            var client = clientFactory.CreateClient();

            // 配置 Request 请求头
            client.MaxResponseContentBufferSize = 2560000;
            client.DefaultRequestHeaders.Add("Accept", "*/*");
            client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
            client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.9");
            client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36");

            // 异步发送 Get 请求
            var res = await client.GetAsync(url);

            // 确保 HTTP 请求成功，提高程序的可靠性
            res.EnsureSuccessStatusCode();

            // 异步读取响应消息
            var body = await res.Content.ReadAsStringAsync();

            Console.WriteLine(body);
        }
    }
}
